package com.tbit.config.payConfig;

import com.alibaba.fastjson.JSON;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.model.MerConfig;
import com.tbit.uqbike.object.pojo.AdaPayConfig;
import com.tbit.uqbike.webmanager.dao.core.AdaPayConfigDao;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 汇付平台初始化
 *
 * @author <a href="mailto:zhang.zhiliang@tbit.com.cn">Zhang ZhiLiang</a>
 * @version 1.0
 * @see <a href="http://adsl1.tbit.com.cn:21490/pages/viewpage.action?pageId=82182491">订单号规范</a>
 * @since 2025/2/17
 */
@Slf4j
@AllArgsConstructor
@Configuration
public class AdapayConfigUtil {

    private final AdaPayConfigDao adaPayConfigDao;

    @Scheduled(cron = "0/30 * * * * ? ")
    @PostConstruct
    public void init(){
//        log.info("客诉-执行汇付多商户初始化");
        List<AdaPayConfig> adaPayConfigList = adaPayConfigDao.getAll();
        if (adaPayConfigList.isEmpty()) {
            return;
        }
        inti(adaPayConfigList);
    }
    private void inti(List<AdaPayConfig> adaPayConfigList){
        /**
         * debug 模式，开启后有详细的日志
         */
        Adapay.debug = true;

        /**
         * prodMode 模式，默认为生产模式，false可以使用mock模式
         */
        Adapay.prodMode = true;

        Map<String, MerConfig> configMap = new HashMap<>();
        adaPayConfigList.forEach(adaPayConfig -> {
            String key = getMchConfigKey(adaPayConfig);
            MerConfig merConfig = new MerConfig();
            merConfig.setApiKey(adaPayConfig.getApiKey());
            merConfig.setApiMockKey(adaPayConfig.getMockApiKey());
            merConfig.setRSAPrivateKey(adaPayConfig.getRsaPrivateKey());
            configMap.put(key,merConfig);
        });
        try {
            Adapay.initWithMerConfigs(configMap);
        } catch (Exception e) {
            log.error("汇付初始化商户配置失败，入参：{}，异常信息：{}", JSON.toJSONString(configMap), e);
        }
    }
    public static String getMchConfigKey(AdaPayConfig adaPayConfig) {
        return String.format("%s-%s", adaPayConfig.getAccountId(), adaPayConfig.getPay_channel());
    }

}
